const Service = require('egg').Service;
const _ = require('lodash');

class CampaignService extends Service {
  async list(data) {
    const condition = {};
    condition.deleted = false;
    condition.title = new RegExp(data.title);
    if (data.pcode != '') {
      condition.pcode = data.pcode;
    }

    const campaigns = await this.app.model.Campaign.find(condition, {
      title: 1,
      pcode: 1,
      start: 1,
      end: 1,
      enabled: 1,
    })
      .sort({
        create_time: -1,
      })
      .limit(parseInt(data.pageSize))
      .skip((data.pageIndex - 1) * data.pageSize);

    const total = await this.app.model.Campaign.count(condition);
    return {
      total: total,
      list: campaigns,
      pageIndex: data.pageIndex,
    };
  }

  async update(id, data) {
    // 更新campaign
    const campaign = _.omit(data, ['pcode', 'entryUrl', 'awards']);
    const v = await this.app.model.Campaign.update({
      _id: id,
    }, campaign);

    return v;
  }

  // 激活，禁用活动
  async changeStatus(id, status) {
    return await this.app.model.Campaign.update({
      _id: id,
    }, {
      enabled: status,
      update_time :new Date(),
    });
  }

  // 活动新增奖品
  async addCampaignAward(campaign_id, award_id, data) {
    const awardInfo = await this.app.model.Award.findById(award_id);
    if (!awardInfo) {
      throw new Error('没有这个奖品');
    }
    if (awardInfo.remaining_inventory < data.limit) {
      throw new Error(`该奖品库存不够，仅剩${awardInfo.remaining_inventory}件`);
    }
    return {
      campaign: await this.app.model.Campaign.update({'_id': campaign_id}, {
        $push: {
          awards: data,
        },
      }),
      award: await this.app.model.Award.update({'_id': award_id}, {
        $push: {
          campaign: this.app.__mongoose.Types.ObjectId(campaign_id),
        },
        $inc: {
          remaining_inventory: data.limit * -1,
        },
      }),
    };
  }

  // 活动删除奖品
  async deleteCampaignAward(campaign_id, award_id, data) {
    return {
      campaign: await this.app.model.Campaign.update({'_id': campaign_id}, {
        $pull: {
          awards: {_id: this.app.__mongoose.Types.ObjectId(award_id)},
        },
      }),
      award: await this.app.model.Award.update({'_id': award_id}, {
        $inc:{
          remaining_inventory: data.remain
        },
        $pull: {
          campaign: this.app.__mongoose.Types.ObjectId(campaign_id),
        },
      }),
    };
  }

  // 活动更新奖品，概率，数量总数
  async updateCampaignAward(campaign_id, award_id, data) {
    const awardInfo = await this.app.model.Award.findById(award_id);
    if (!awardInfo) {
      throw new Error('没有这个奖品');
    }
    if (awardInfo.remaining_inventory < data.inc) {
      throw new Error(`该奖品库存不够，仅剩${awardInfo.remaining_inventory}件`);
    }
    return {
      campaign: await this.app.model.Campaign.update({'_id': campaign_id, 'awards._id': award_id}, {
        $set: {
          'awards.$.probability': data.probability,
          'awards.$.enabled': data.enabled,
        },
        $inc: {
          'awards.$.limit': data.inc,
          'awards.$.remain': data.inc,
        },
      }),
      award: await this.app.model.Award.update({'_id': award_id}, {
        $inc: {
          remaining_inventory: data.inc * -1,
        },
      }),
    };
  }

  // 删除活动
  async delete(id) {

    // 逻辑删
    const result = await this.app.model.Campaign.update(
      {
        _id: id,
      }, {
        deleted: true,
      });

    return result;
  }
}

module.exports = CampaignService;
